using Microsoft.Extensions.Logging;
using SumerCoreDevOps.Domain.Entities;
using SumerCoreDevOps.Infrastructure.Data;

namespace SumerCoreDevOps.Infrastructure.Artifacts;

/// <summary>
/// 构建产物管理器
/// </summary>
public class BuildArtifactManager
{
    private readonly FreeSQLProvider _dbProvider;
    private readonly ILogger<BuildArtifactManager> _logger;

    public BuildArtifactManager(FreeSQLProvider dbProvider, ILogger<BuildArtifactManager> logger)
    {
        _dbProvider = dbProvider;
        _logger = logger;
    }

    /// <summary>
    /// 创建构建产物记录
    /// </summary>
    public async Task<BuildArtifact> CreateArtifactAsync(
        long nodeId,
        long taskId,
        long? buildHistoryId,
        string name,
        string type,
        long fileSize,
        string filePath,
        string md5Hash,
        string? description = null,
        int? retentionDays = null)
    {
        var artifact = new BuildArtifact
        {
            NodeId = nodeId,
            TaskId = taskId,
            BuildHistoryId = buildHistoryId,
            Name = name,
            Type = type,
            FileSize = fileSize,
            FilePath = filePath,
            Md5Hash = md5Hash,
            Description = description,
            CreatedAt = DateTime.UtcNow,
            ExpiresAt = retentionDays.HasValue ? DateTime.UtcNow.AddDays(retentionDays.Value) : null,
            IsDeleted = false,
            DownloadCount = 0
        };

        await _dbProvider.Orm.Insert(artifact).ExecuteAffrowsAsync();

        _logger.LogInformation("创建构建产物: Id={Id}, NodeId={NodeId}, Name={Name}, Size={Size} bytes",
            artifact.Id, artifact.NodeId, artifact.Name, artifact.FileSize);

        return artifact;
    }

    /// <summary>
    /// 获取产物
    /// </summary>
    public async Task<BuildArtifact?> GetArtifactAsync(long id)
    {
        return await _dbProvider.Orm
            .Select<BuildArtifact>()
            .Where(a => a.Id == id && !a.IsDeleted)
            .FirstAsync();
    }

    /// <summary>
    /// 按任务 ID 获取产物列表
    /// </summary>
    public async Task<List<BuildArtifact>> GetArtifactsByTaskIdAsync(long taskId)
    {
        return await _dbProvider.Orm
            .Select<BuildArtifact>()
            .Where(a => a.TaskId == taskId && !a.IsDeleted)
            .OrderByDescending(a => a.CreatedAt)
            .ToListAsync();
    }

    /// <summary>
    /// 按构建历史 ID 获取产物列表
    /// </summary>
    public async Task<List<BuildArtifact>> GetArtifactsByBuildHistoryIdAsync(long buildHistoryId)
    {
        return await _dbProvider.Orm
            .Select<BuildArtifact>()
            .Where(a => a.BuildHistoryId == buildHistoryId && !a.IsDeleted)
            .OrderByDescending(a => a.CreatedAt)
            .ToListAsync();
    }

    /// <summary>
    /// 增加下载次数
    /// </summary>
    public async Task IncrementDownloadCountAsync(long id)
    {
        await _dbProvider.Orm
            .Update<BuildArtifact>()
            .Set(a => a.DownloadCount + 1)
            .Where(a => a.Id == id)
            .ExecuteAffrowsAsync();

        _logger.LogDebug("产物下载次数+1: Id={Id}", id);
    }

    /// <summary>
    /// 删除产物（软删除）
    /// </summary>
    public async Task<bool> DeleteArtifactAsync(long id)
    {
        var rows = await _dbProvider.Orm
            .Update<BuildArtifact>()
            .Set(a => a.IsDeleted, true)
            .Where(a => a.Id == id)
            .ExecuteAffrowsAsync();

        _logger.LogInformation("删除构建产物: Id={Id}", id);

        return rows > 0;
    }

    /// <summary>
    /// 清理过期产物
    /// </summary>
    public async Task<int> CleanupExpiredArtifactsAsync()
    {
        var expiredArtifacts = await _dbProvider.Orm
            .Select<BuildArtifact>()
            .Where(a => !a.IsDeleted && a.ExpiresAt.HasValue && a.ExpiresAt.Value < DateTime.UtcNow)
            .ToListAsync();

        int deletedCount = 0;

        foreach (var artifact in expiredArtifacts)
        {
            // 删除物理文件
            try
            {
                if (File.Exists(artifact.FilePath))
                {
                    File.Delete(artifact.FilePath);
                    _logger.LogInformation("删除过期产物文件: {FilePath}", artifact.FilePath);
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "删除产物文件失败: {FilePath}", artifact.FilePath);
            }

            // 标记为已删除
            await DeleteArtifactAsync(artifact.Id);
            deletedCount++;
        }

        if (deletedCount > 0)
        {
            _logger.LogInformation("清理了 {Count} 个过期产物", deletedCount);
        }

        return deletedCount;
    }

    /// <summary>
    /// 获取产物统计信息
    /// </summary>
    public async Task<ArtifactStatistics> GetStatisticsAsync()
    {
        var totalCount = await _dbProvider.Orm
            .Select<BuildArtifact>()
            .Where(a => !a.IsDeleted)
            .CountAsync();

        var totalSize = await _dbProvider.Orm
            .Select<BuildArtifact>()
            .Where(a => !a.IsDeleted)
            .SumAsync(a => a.FileSize);

        var totalDownloads = await _dbProvider.Orm
            .Select<BuildArtifact>()
            .Where(a => !a.IsDeleted)
            .SumAsync(a => a.DownloadCount);

        return new ArtifactStatistics
        {
            TotalCount = totalCount,
            TotalSize = (long)totalSize,
            TotalDownloads = (int)totalDownloads
        };
    }
}

/// <summary>
/// 产物统计信息
/// </summary>
public class ArtifactStatistics
{
    public long TotalCount { get; set; }
    public long TotalSize { get; set; }
    public int TotalDownloads { get; set; }
}
